/**
 * @Date 2023-02-23 11:49:30
 * @Remark
 */

// config
// 路由
import { dataState } from "state/global";
import MainRoutes from "./MainRoutes";
// 其它
import { completeLink, getCodeFromPath } from "./format";

/**
 * 树和列表的组成项统一转换方法
 */
function getMenuFromRoute(item: AppRouteItem) {
  const url = completeLink(item.path); // 添加main前缀
  const result: AppMenu = {
    label: item.name,
    icon: item.icon,
    // key: getCodeFromPath(url),
    key:item.code||getCodeFromPath(url),
    url,
    hidden: item.hidden,
  };
  return result;
}

/**
 * 获得一个菜单树
 * 在生成左侧菜单时使用
 */
export function getMenuTreeFromRoutes(): AppMenu[] {
  
  let flatMenu:AppRouteItem[] = [...MainRoutes]
  const loop = (list: AppRouteItem[]): AppMenu[] => {
    const result = list.map((el) => {
      const item = getMenuFromRoute(el);
      if (el.children && el.children.length > 0) {
        flatMenu = [...flatMenu,...el.children] 
        const childrenList = loop(el.children);
        if (childrenList && childrenList.length > 0) {
          item.children = childrenList;
          
        }
      }
      return item;
    });
    console.log('-----------Flatmenu',flatMenu)
    dataState.routeItems = flatMenu
    return result;
  };

  const tree = loop(MainRoutes);
  return tree;
}

/**
 * 获得一个菜单列表
 * 在顶部标签区域和菜单模块需要使用
 */
export function getMenuListFromRoutes(): AppMenu[] {
  const result: AppMenu[] = [];
  const loop = (list: AppRouteItem[]) => {
    list.forEach((el) => {
      result.push(getMenuFromRoute(el));
      if (el.children && el.children.length > 0) {
        loop(el.children);
      }
    });
  };
  loop(MainRoutes);
  return result;
}
